package org.jenkinsci.plugins.p4scm.utils;

import java.io.IOException;
import java.io.InputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TimedStreamCloser extends Thread{
    
    private static final Logger logger = LoggerFactory.getLogger(TimedStreamCloser.class);

    private long seconds;
    private InputStream in;
    private long timeout;
    private boolean keepRunning = true;
    private boolean timedOut = false;
    private Object lock;
    
    public TimedStreamCloser(InputStream in, long timeout) throws IOException {
        this.in = in;
        this.timeout = timeout;
        lock = this;
    }
    
    public void reset() {
        synchronized (lock) {
            seconds = 0;
        }
    }
    
    public void close() {
        keepRunning = false;
        try {
            in.close();
        } catch (IOException ex) {
            logger.error("Fail to close", ex);
        }
    }

    @Override
    public void run() {
        if (timeout < 0) return; //no timeout, so do nothing
        this.reset();
        
        while(keepRunning) {
            if(seconds > timeout){
                timedOut = true;
                close();
                break;
            }

            try {
                Thread.sleep(1000);
                seconds++;
            } catch (InterruptedException ex) {
                close();
                break;
            }
        }
    }
    
    public boolean timedOut() {
        return timedOut;
    }
}
